package com.youhong.teethcare;

import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.youhong.cuptime.blesdk.BleService;
import com.youhong.teethcare.customviews.BrushAreaShowView;
import com.youhong.teethcare.customviews.CountDownmageView;
import com.youhong.teethcare.customviews.RxRoundProgress;
import com.youhong.teethcare.customviews.TeethModelRelativeLayout;
import com.youhong.teethcare.dialogs.ChargeNotificationDialog;
import com.youhong.teethcare.javabeans.BrushingRecord;
import com.youhong.teethcare.services.Common;
import com.youhong.teethcare.utils.BrushShowUtils;
import com.youhong.teethcare.utils.DBHelper;
import com.youhong.teethcare.utils.DialogUtil;
import com.youhong.teethcare.utils.MyUtilsKt;
import com.youhong.teethcare.utils.PreferencesUtils;
import com.youhong.teethcare.utils.ScreenUtils;
import com.youhong.teethcare.utils.ToastUtil;
import com.youhong.teethcare.utils.Util;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class BrushingFragment extends Fragment implements View.OnClickListener {

    //    TeethModelRelativeLayout teethMode;
    ImageView iv_connect;
    ImageView iv_brush;
    ImageView iv_play;
    //CountDownmageView iv_countdown;

    AnimationDrawable mAnim;
    RxRoundProgress mProgressBar;
    TextView tv_surface;
    RelativeLayout relativeLayoutArea;
    Dialog dialog_chargeNotification;

    public BrushingFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_brushing, container, false);
        getViews(v);

        IntentFilter filter = new IntentFilter();
        filter.addAction(BleService.ACTION_GATT_DISCONNECTED);
        filter.addAction(BleService.ACTION_DATA_AVAILABLE);
        filter.addAction(BleService.ACTION_GATT_SERVICES_DISCOVERED);
        getActivity().registerReceiver(receiver, filter);
        dbHelper = DBHelper.getDbHelper(getContext());
        return v;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (MainActivity.mDevice == null) {

            ((MainActivity) getActivity()).connect();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
        //清空Handler确保不会出现内存泄漏，
        handler.removeCallbacksAndMessages(null);


        if (MainActivity.mDevice != null && MainActivity.isBrushWork == true) {
            MainActivity.mDevice.guideBrushing((byte) 0x0, (byte) 0x0);
            MainActivity.isBrushWork = false;
        }
        //重置BrushingFragment 类对象里的数据值， 因为在MainActivity 里Remove 这个Fragment，
        //会导致触发OnDestroy 回调 , 但是MainActivity里 Add这个Fragment 并不会重新执行这个类的构造函数。
        reset();
    }

    void showDeviceState(boolean isConnect) {
        iv_connect.setImageDrawable(getResources().getDrawable(isConnect ? R.mipmap.icon_connected : R.mipmap.icon_unconnected));

    }

    BrushAreaShowView brushAreaShowView;
    TextView textViewCountDown;
    EditText editText;
    Button button;
    private void getViews(View v) {
        brushAreaShowView = v.findViewById(R.id.BrushAreaShowView);
        textViewCountDown = v.findViewById(R.id.tvCountDown);
        relativeLayoutArea=v.findViewById(R.id.rlArea);
        editText = v.findViewById(R.id.edittextArea);
        button = v.findViewById(R.id.btTest);
        button.setOnClickListener(this);
        Bitmap bitmapBackground = BitmapFactory.decodeResource(getResources(), R.drawable.brush_realtime_bg);
        brushAreaShowView.updateBg(bitmapBackground);
        iv_connect = v.findViewById(R.id.brushing_iv_connect);
        iv_connect.setOnClickListener(this);

        //判断是否与设备保持连接
        if (MainActivity.mDevice != null) {
            showDeviceState(MainActivity.mDevice.isConnected());
        } else {
            showDeviceState(false);
        }

        iv_brush = v.findViewById(R.id.brushing_teethBrush);

        //    teethMode = v.findViewById(R.id.brushing_teethModel);
        int window_width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        int window_height = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        // teethMode.resize(window_width, window_height);

        mProgressBar = v.findViewById(R.id.brushing_roundProgressBar);
        iv_play = v.findViewById(R.id.brushing_iv_play);
        iv_play.setOnClickListener(this);
        //iv_countdown = v.findViewById(R.id.brushing_iv_countDown);
        tv_surface = v.findViewById(R.id.brushing_tv_surface);
        setmAnim();
    }

    void setmAnim(){


    }
    /**
     * 切换牙刷的显示区域
     **/
    private void changeDisplay(int area) {

        int screen_width = relativeLayoutArea.getWidth();
        int screen_height = relativeLayoutArea.getHeight();
//
        int width=ScreenUtils.dip2px(getContext(),160);
        int height=ScreenUtils.dip2px(getContext(),70);
        if(area>4){
            width=ScreenUtils.dip2px(getContext(),160);
            height=ScreenUtils.dip2px(getContext(),160);
        }
        int animResId=R.drawable.anim_bottom_bottom;
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) iv_brush.getLayoutParams();
        params.leftMargin=0;
        params.topMargin=0;
        switch (area) {
            case 1:
                animResId=R.drawable.anim_bottom_bottom;
                params.topMargin = (int) (screen_height-height/2);
                break;
            case 2:
                animResId=R.drawable.anim_bottom_top;
                params.topMargin = (int) (screen_height-height);
                break;
            case 3:
                animResId=R.drawable.anim_top_top;
                params.topMargin = (int) (-height/2);
                break;
            case 4:
                animResId=R.drawable.anim_top_bottom;
                params.topMargin =0;
                break;
            case 5:
                animResId=R.drawable.anim_leftbottom_left;
                params.leftMargin = (int) (-width/3);
                params.topMargin = (int) ( screen_height/2+height/2);
                break;
            case 6:
                animResId=R.drawable.anim_leftbottom_middle;
                params.leftMargin = (int) (-width/4);
                params.topMargin = (int) ( screen_height/2+height/2);
                break;
            case 7:
                animResId=R.drawable.anim_leftbottom_right;
                params.topMargin = (int) ( screen_height/2+height/2);
                break;
            case 8:
                animResId=R.drawable.anim_lefttop_left;
                params.leftMargin = (int) (-width/2);
                params.topMargin = (int) (height/3);
                break;
            case 9:
                animResId=R.drawable.anim_lefttop_middle;
                params.leftMargin = (int) (-width/3);
                params.topMargin = (int) (height/3);
                break;
            case 10:
                animResId=R.drawable.anim_lefttop_right;
                params.leftMargin = (int) (-width/4);
                params.topMargin = (int) (height/3);
                break;
            case 11:
                animResId=R.drawable.anim_rightbottom_right;
                params.leftMargin = screen_width-width/2;
                params.topMargin = (int) ( screen_height/2+height/2);
                break;
            case 12:
                animResId=R.drawable.anim_rightbottom_middle;
                params.leftMargin = (int) (screen_width-width*3/4f);
                params.topMargin = (int) ( screen_height/2+height/2);
                break;
            case 13:
                animResId=R.drawable.anim_rightbottom_left;
                params.leftMargin = screen_width-width;
                params.topMargin =  screen_height/2+height/2;
                break;
            case 14:
                animResId=R.drawable.anim_righttop_right;
                params.leftMargin = screen_width-width/3;
                params.topMargin = (int) (height/3);
                break;
            case 15:
                animResId=R.drawable.anim_righttop_middle;
                params.leftMargin = (int) (screen_width-width/2f);
                params.topMargin = (int) (height/3);
                break;
            case 16:
                animResId=R.drawable.anim_righttop_left;
                params.leftMargin = (int) (screen_width-width*2/3f);
                params.topMargin = (int) (height/3);
                break;
        }
        Glide.with(this).asGif().load(animResId).into(iv_brush);
        params.width = (int) (width);
        params.height = (int) (height);
        iv_brush.setLayoutParams(params);
      //  mAnim = (AnimationDrawable) iv_brush.getBackground();
//        mAnim.start();
    }

    Calendar cal_start;
    public long c_start, c_end;
    int countDown = 0;
    final String BrushMode = "BrushMode";

    private void startBrushing() {
        MainActivity.isBrushingStart = true;

        iv_play.setVisibility(View.GONE);
        //iv_countdown.setVisibility(View.GONE);
        textViewCountDown.setVisibility(View.GONE);
        MainActivity.mDevice.guideBrushing((byte) 0x1, (byte) 0x1);
        MainActivity.isBrushWork = true;
        mProgressBar.setVisibility(View.VISIBLE);
        changeDisplay(1);

        handler.postDelayed(runnable_areaCountDown, 20000);
        iv_brush.setVisibility(View.VISIBLE);

        //记录开始时间，用于计算刷牙总时长
        cal_start = Calendar.getInstance();
        c_start = System.currentTimeMillis();
    }

    Runnable runnable_countDown = new Runnable() {
        @Override
        public void run() {

            countDown--;
            if (countDown == 0) {

                startBrushing();

            } else {

                textViewCountDown.setVisibility(View.VISIBLE);
                textViewCountDown.setText("" + countDown);
                //iv_countdown.invalidate();
                handler.postDelayed(this, 1000);
            }
        }
    };

    //当从设备处接受到50条刷牙状态正确的数据时，就切换至下一区域 ,每条数据 2%
    int area_count = 0;
    int area = 1;

    //暂停前保存的刷牙毫秒数。
    public int previousBrushTime = 0;

    public void brushProgress(byte area, byte isCorrect) {

        //是否结束，手动结束或者，超过5分钟结束
        if (area == (byte) 0x99) {
            finishBrushing();
            return;
        }

        //用户按了牙刷上的按键， 开始进行指导刷牙。
        if (area == (byte) 0x88) {

            //APP 刷牙指导处于暂停状态， 需要恢复，此处功能和在APP 上点击Continue 是同样的效果。
            if (isSusependState == true) {

                resumeBrushing();
                return;
            }
            //当启动倒计时后，屏蔽用户再次按按键启动的情况。

            //用户按下牙刷上按键后，立刻开始刷牙
            if (!MainActivity.isBrushingStart) {

                startBrushing();
                return;
            }
        }

        if (area_count == 50) {

            //切换区域
            if (isAfterwardsBrush) {

                afterwardsSwitchArea(false);

            } else {

                switchArea();
            }
        } else {

            if (isCorrect == 1) {

                area_count++;
                mProgressBar.setPercent(area_count * 2);
                mProgressBar.setCricleProgressColor(Color.WHITE);
                mProgressBar.invalidate();


                tv_surface.setTextColor(Color.WHITE);
                //百分比显示
                mProgressBar.setTextVersion(0);
                //根据区域对顶部的文字进行变换

                if (area == 1) {
                    tv_surface.setText(R.string.surface1);

                } else if (area == 2) {

                    tv_surface.setText(R.string.surface2);

                } else if (area == 3) {

                    tv_surface.setText(R.string.surface3);

                } else if (area == 4) {

                    tv_surface.setText(R.string.surface4);

                } else if (area == 5) {

                    tv_surface.setText(R.string.surface5);

                } else if (area == 6) {

                    tv_surface.setText(R.string.surface6);

                } else if (area == 7) {

                    tv_surface.setText(R.string.surface7);

                } else if (area == 8) {

                    tv_surface.setText(R.string.surface8);

                } else if (area == 9) {

                    tv_surface.setText(R.string.surface9);

                } else if (area == 10) {

                    tv_surface.setText(R.string.surface10);

                } else if (area == 11) {

                    tv_surface.setText(R.string.surface11);

                } else if (area == 12) {

                    tv_surface.setText(R.string.surface12);

                } else if (area == 13) {

                    tv_surface.setText(R.string.surface13);


                } else if (area == 14) {

                    tv_surface.setText(R.string.surface14);

                } else if (area == 15) {

                    tv_surface.setText(R.string.surface15);


                } else if (area == 16) {

                    tv_surface.setText(R.string.surface16);
                }

            } else {

                tv_surface.setTextColor(Color.RED);

                mProgressBar.setTextVersion(1);

                if (area == 1) {
                    tv_surface.setText(R.string.surface_error1);


                } else if (area == 2) {

                    tv_surface.setText(R.string.surface_error2);

                } else if (area == 3) {

                    tv_surface.setText(R.string.surface_error3);

                } else if (area == 4) {

                    tv_surface.setText(R.string.surface_error4);

                } else if (area == 5) {

                    tv_surface.setText(R.string.surface_error5);

                } else if (area == 6) {

                    tv_surface.setText(R.string.surface_error6);

                } else if (area == 7) {

                    tv_surface.setText(R.string.surface_error7);

                } else if (area == 8) {

                    tv_surface.setText(R.string.surface_error8);

                } else if (area == 9) {

                    tv_surface.setText(R.string.surface_error9);

                } else if (area == 10) {

                    tv_surface.setText(R.string.surface_error10);

                } else if (area == 11) {

                    tv_surface.setText(R.string.surface_error11);

                } else if (area == 12) {

                    tv_surface.setText(R.string.surface_error12);

                } else if (area == 13) {
                    tv_surface.setText(R.string.surface_error13);

                } else if (area == 14) {

                    tv_surface.setText(R.string.surface_error14);

                } else if (area == 15) {

                    tv_surface.setText(R.string.surface_error15);

                } else if (area == 16) {

                    tv_surface.setText(R.string.surface_error16);

                }

                mProgressBar.setCricleProgressColor(Color.RED);
                mProgressBar.invalidate();
            }
        }
    }

    byte bytes1, bytes2, bytes3, bytes4, bytes5, bytes6;

    List<Integer> unclearArea = new ArrayList<>();

    private void switchArea() {

        //清空倒计时
        handler.removeCallbacks(runnable_areaCountDown);

        //判断该区域是否按照要求刷完
        if (area_count == 50) {
            switch (area) {
                case 0:
                    break;
                case 1:
                    bytes1 |= 0x1;
                    break;
                case 2:
                    bytes1 |= 0x4;
                    break;
                case 3:
                    bytes2 |= 0x1;
                    break;
                case 4:
                    bytes2 |= 0x4;
                    break;
                case 5:
                    bytes3 |= 0x1;
                    break;
                case 6:
                    bytes3 |= 0x2;
                    break;
                case 7:
                    bytes3 |= 0x4;
                    break;
                case 8:
                    bytes4 |= 0x1;
                    break;
                case 9:
                    bytes4 |= 0x2;
                    break;
                case 10:
                    bytes4 |= 0x4;
                    break;
                case 11:
                    bytes5 |= 0x1;
                    break;
                case 12:
                    bytes5 |= 0x2;
                    break;
                case 13:
                    bytes5 |= 0x4;
                    break;
                case 14:
                    bytes6 |= 0x1;
                    break;
                case 15:
                    bytes6 |= 0x2;
                    break;
                case 16:
                    bytes6 |= 0x4;
                    break;
            }

            //切换牙齿区域状态显示
            // teethMode.areaDisplay(bytes1, bytes2, bytes3, bytes4, bytes5, bytes6);
            //teethMode.invalidate();
            List<Integer> areaList = MyUtilsKt.getArea(bytes1, bytes2, bytes3, bytes4, bytes5, bytes6);
            brushAreaShowView.updateAreaList(areaList);
        } else {
            //记录有哪些区域没有刷干净
            unclearArea.add(area);
        }

        area++;
        area_count = 0;
        //当16个区域全部刷完后
        if (area > 16) {

            //所有的区域并没有刷干净，提示用户是否继续刷牙
            if (unclearArea.size() != 0) {

                //切换至Afterwards刷牙模式
                isAfterwardsBrush = true;
                isAppClose = true;

                MainActivity.isBrushWork = false;
                //先关闭牙刷。
                MainActivity.mDevice.guideBrushing((byte) 0x0, (byte) 0x0);

                DialogUtil.showModalDialog(getContext(), R.string.newString_33, R.string.strings84, R.string.newString_35, R.string.newString_34,

                        new Runnable() {
                            @Override
                            public void run() {
                                isSusependState = false;
                                afterwardsSwitchArea(true);
                            }
                        },
                        new Runnable() {
                            @Override
                            public void run() {

                                isAfterwardsBrush = false;
                                isAfterwardBrushOvered = true;
                                finishBrushing();
                                return;
                            }
                        }
                );
                return;
            } else {
                //所有区域全部正常刷完，结束刷牙
                finishBrushing();
                return;


            }
        }

        MainActivity.mDevice.guideBrushing((byte) 0x2, (byte) area);

        //切换牙刷动画。
        changeDisplay(area);

        //清空进度条
        mProgressBar.setPercent(0);
        mProgressBar.setCricleProgressColor(Color.WHITE);
        mProgressBar.invalidate();

        //设置区域倒计时
        handler.postDelayed(runnable_areaCountDown, 20000);
    }

    private void afterwardsSwitchArea(boolean isFirstTimeIn) {

        if (!isFirstTimeIn) {

            switch (area) {
                case 0:
                    break;
                case 1:
                    bytes1 |= 0x1;
                    break;
                case 2:
                    bytes1 |= 0x4;
                    break;
                case 3:
                    bytes2 |= 0x1;
                    break;
                case 4:
                    bytes2 |= 0x4;
                    break;
                case 5:
                    bytes3 |= 0x1;
                    break;
                case 6:
                    bytes3 |= 0x2;
                    break;
                case 7:
                    bytes3 |= 0x4;
                    break;
                case 8:
                    bytes4 |= 0x1;
                    break;
                case 9:
                    bytes4 |= 0x2;
                    break;
                case 10:
                    bytes4 |= 0x4;
                    break;
                case 11:
                    bytes5 |= 0x1;
                    break;
                case 12:
                    bytes5 |= 0x2;
                    break;
                case 13:
                    bytes5 |= 0x4;
                    break;
                case 14:
                    bytes6 |= 0x1;
                    break;
                case 15:
                    bytes6 |= 0x2;
                    break;
                case 16:
                    bytes6 |= 0x4;
                    break;
            }
        } else {

        }

        //切换牙齿区域状态显示
        //teethMode.areaDisplay(bytes1, bytes2, bytes3, bytes4, bytes5, bytes6);
        //  teethMode.invalidate();
        List<Integer> areaList = MyUtilsKt.getArea(bytes1, bytes2, bytes3, bytes4, bytes5, bytes6);
        brushAreaShowView.updateAreaList(areaList);
        //全部区域都刷完了。 结束刷牙
        if (unclearArea.size() == 0) {

            finishBrushing();
            return;

        } else {

            area_count = 0;
            //切换至下一个未刷干净的区域
            area = unclearArea.get(0);
            unclearArea.remove(0);

            //第一次进入，再次启动牙刷，否则只是切换区域
            if (isFirstTimeIn) {
                MainActivity.mDevice.guideBrushing((byte) 0x1, (byte) area);

            } else {
                MainActivity.mDevice.guideBrushing((byte) 0x2, (byte) area);
            }

            //切换牙刷动画。
            changeDisplay(area);
            //清空进度条
            mProgressBar.setPercent(0);
            mProgressBar.setCricleProgressColor(Color.WHITE);
            mProgressBar.invalidate();

        }
    }

    boolean isSusependState = false;
    boolean isAfterwardsBrush = false;
    boolean isAppClose = false;
    boolean isAfterwardBrushOvered = false;

    private void finishBrushing() {

        //计算刷牙时长，并存储刷牙区域结果
        MainActivity.isBrushWork = false;

        if (isAfterwardBrushOvered) {

            saveHistory();
            reset();

            ((MainActivity) getActivity()).switchToHistoryFragment();
            return;
        }

        if (isSusependState == true) {
            return;
        }

        c_end = System.currentTimeMillis();
        if (c_start == 0) {
            return;
        }
        long miliseconds = c_end - c_start;

        //未刷完，暂停刷牙
        if (isAppClose == true) {
            //弹出提示框前的关闭，不做任何处理
            isSusependState = true;
            isAppClose = false;
            return;
        } else if ((isAfterwardsBrush == true && unclearArea.size() != 0) || (area <= 16 && isAfterwardsBrush == false)) {
            previousBrushTime += miliseconds;

            //给c_start 赋值和c_end 同样的值，以免重复累加时间。
            //当再次恢复刷牙的时候，c_start 又会被重新赋值
            c_start = c_end;
            //暂停动画
            mAnim.stop();
            handler.removeCallbacksAndMessages(null);
            isSusependState = true;

            DialogUtil.showModalDialog(getContext(), R.string.strings85, R.string.strings84, R.string.strings86, R.string.strings87,

                    new Runnable() {
                        @Override
                        public void run() {
                            resumeBrushing();
                        }
                    },
                    new Runnable() {
                        @Override
                        public void run() {
                            //如果刷牙时长超过60s再保存数据，否则不保存数据

                            if (miliseconds + previousBrushTime > 60000) {
                                saveHistory();
                                reset();

                                ((MainActivity) getActivity()).switchToHistoryFragment();

                            } else {
                                reset();

                            }
                        }
                    }
            );
            return;
        }

        //所有区域都已刷完，保存数据。并跳转至刷牙历史界面。
        saveHistory();
        reset();


        MainActivity.isBrushWork = false;
        ((MainActivity) getActivity()).switchToHistoryFragment();
    }

    public void mainActivityFinishBurshing() {

        //所有区域都已刷完，保存数据。并跳转至刷牙历史界面。
        c_end = System.currentTimeMillis();
        saveHistory();
        reset();

        MainActivity.isBrushWork = false;
        ((MainActivity) getActivity()).switchToHistoryFragment();
    }

    //恢复暂停状态
    private void resumeBrushing() {
        //恢复状态，给牙刷发送启动命令
        if (MainActivity.mDevice != null) {

            DialogUtil.dismissModalDialog1();

            isSusependState = false;
            c_start = System.currentTimeMillis();

            MainActivity.mDevice.guideBrushing((byte) 0x1, (byte) area);
            MainActivity.isBrushWork = true;

            //恢复每个区域 20s的看门狗
            handler.postDelayed(runnable_areaCountDown, 20000);

            mAnim.start();
        }
    }
    final String BrushLv = "BrushLv";

    /**
     * 连接app测量，通过app把刷牙模式，刷牙等级发送给固件，让固件保存（0x23发送）
     * 再次读取的时候固件会返回对应的数据（0x15读取）
     * 0x23的9，10下标位暂时没有用到，现在定义为（刷牙模式，刷牙等级），0x15对应的下标位是10，11
     */
    private void saveHistory() {

        long miliseconds = c_end - c_start;

        //累加上暂停前的刷牙时长.
        miliseconds += previousBrushTime;
        float ratio = (float) (miliseconds / 1000) / (float) Common.userInfo.getBrushTime();

        if (ratio > 1f) {
            ratio = 1f;
        }

        Common.userInfo.SyncToLocal(getContext());
        int mode = PreferencesUtils.ReadFromPreferencesInt(getContext(), BrushMode);
        int level = PreferencesUtils.ReadFromPreferencesInt(getContext(),BrushLv);

        BrushingRecord record = new BrushingRecord();
        record.setUid(Common.userInfo.getToken());
        record.setBrushMode(mode);
        record.setBrushLevel(level);
        record.setStartTime(cal_start);
        record.setTotalTime((int) (miliseconds / 1000));
        record.setArea1(bytes1);
        record.setArea2(bytes2);
        record.setArea3(bytes3);
        record.setArea4(bytes4);
        record.setArea5(bytes5);
        record.setArea6(bytes6);

        int surfaceCount = calculatePercent();
        record.setSurfaceCount(surfaceCount);
        int surfacePercent = (int) ((float) surfaceCount / (float) 16 * 100);

        int score = 0;
        /**
         在线刷牙60%以上奖励30积分，80%以上奖励50积分，100%奖励60积分
         */
        if (surfacePercent == 100) {
            score = 60;

        } else if (surfaceCount > 80) {

            score = 50;
        } else if (surfaceCount > 60) {
            score = 30;
        }

        Common.userInfo.setScore((int) score + Common.userInfo.getScore());
        //更新最新同步时间，当下次再同步历史数据时，会过滤掉这条数据
        Common.userInfo.setLastSyncTime(System.currentTimeMillis());
        Common.userInfo.SyncToLocal(getContext());

        record.setPercent(surfacePercent);

        //如果指导刷牙数据刷牙时长大于5分钟，则不保存.
        if (record.getTotalTime() > 300) {
            return;
        }

        DBHelper.getDbHelper(getContext()).insertBrushRecord(record);
        MainActivity.mDevice.saveBrushRecord(record);
    }

    //恢复当前BrushingFragment的状态和全局变量到最初始的状态。
    private void reset() {

        bytes1 = 0;
        bytes2 = 0;
        bytes3 = 0;
        bytes4 = 0;
        bytes5 = 0;
        bytes6 = 0;
        //  teethMode.areaDisplay(bytes1, bytes2, bytes3, bytes4, bytes5, bytes6);
        tv_surface.setText("");
        List<Integer> areaList = MyUtilsKt.getArea(bytes1, bytes2, bytes3, bytes4, bytes5, bytes6);
        brushAreaShowView.updateAreaList(areaList);
        area_count = 0;
        area = 1;
        countDown = 0;
        iv_play.setVisibility(View.VISIBLE);
        mProgressBar.setPercent(0);
        mProgressBar.setVisibility(View.GONE);
        c_start = 0;
        c_end = 0;
        previousBrushTime = 0;
        MainActivity.isBrushingStart = false;
        isSusependState = false;
        isAppClose = false;
        isAfterwardsBrush = false;
        isAfterwardBrushOvered = false;
        unclearArea.clear();


        iv_brush.setVisibility(View.GONE);

    }

    //计算刷牙积分
    private int calculatePercent() {
        int surfaceCount = 0;

        surfaceCount += (calculateSurface(bytes1));
        surfaceCount += (calculateSurface(bytes2));
        surfaceCount += (calculateSurface(bytes3));
        surfaceCount += (calculateSurface(bytes4));
        surfaceCount += (calculateSurface(bytes5));
        surfaceCount += (calculateSurface(bytes6));
        return surfaceCount;
    }

    private int calculateSurface(byte surface) {
        int score = 0;

        if ((surface & 1) != 0) {
            score++;
        }

        if ((surface & 2) != 0) {
            score++;
        }

        if ((surface & 4) != 0) {
            score++;
        }

        return score;
    }

    //互斥量 用来防止用户点击Play 按键，倒计时同时启动牙刷。导致的问题。
    @Override
    public void onClick(View v) {

        if (v == iv_play) {
            //如果设备还未连接,
            if (MainActivity.mDevice == null) {
                ToastUtil.showShortToast(getContext(), R.string.strings114);
                return;
            }
            //先查询牙刷当前是否处于充电状态，如果是：就弹出Device is Charing 对话框
            //否则：开启倒计时(countDownPrepare())

            MainActivity.mDevice.getBrushingStatus();

        }else if(v==button) {
            int area=Integer.valueOf(editText.getText().toString());
            changeDisplay(area);
            iv_brush.setVisibility(View.VISIBLE);
        }else if (v == iv_connect) {

            if (MainActivity.isBrushingStart) {
                ToastUtil.showShortToast(getContext(), R.string.strings126);
                return;
            }

            isManuallyDisconnected = true;
            ((MainActivity) getActivity()).connect();
        }
    }

    Runnable runnable_iv_close = new Runnable() {
        @Override
        public void run() {
            dialog_chargeNotification = null;
        }
    };

    private void countDownPrepare() {

        countDown = 6;
        iv_play.setVisibility(View.GONE);
        MainActivity.isBrushingStart = true;
        handler.post(runnable_countDown);
        tv_surface.setText(R.string.strings100);
        changeDisplay(1);
       // mAnim = (AnimationDrawable) iv_brush.getBackground();
//        mAnim.stop();
        iv_brush.setVisibility(View.VISIBLE);

    }


    protected Handler handler = new Handler();

    Runnable runnable_areaCountDown = new Runnable() {
        @Override
        public void run() {
            switchArea();
        }
    };
    boolean isManuallyDisconnected = false;
    DBHelper dbHelper;

    //连接后获取牙刷当前状态的标识位。
    boolean isConnectedGettingState = false;
    int brushMode=0;
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction() == BleService.ACTION_GATT_SERVICES_DISCOVERED) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //connectDialog.cancel();
                        iv_connect.setImageDrawable(getResources().getDrawable(R.mipmap.icon_connected));
                        handler.removeCallbacksAndMessages(null);

                        //连接成功后，立刻同步时间

                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                MainActivity.mDevice.syncTime(Calendar.getInstance());
                            }
                        }, 500);
                    }
                });
            } else if (intent.getAction() == BleService.ACTION_GATT_DISCONNECTED) {

                if (isManuallyDisconnected) {
                    isManuallyDisconnected = false;
                    iv_connect.setImageDrawable(getResources().getDrawable(R.mipmap.icon_unconnected));
                    MainActivity.mDevice = null;

                } else {

                    ToastUtil.showShortToast(context, R.string.strings20);

                }
                showDeviceState(false);
            } else if (intent.getAction() == BleService.ACTION_DATA_AVAILABLE) {

                final byte[] values = intent.getByteArrayExtra(BleService.EXTRA_DATA);

                switch (values[0]) {

                    case 0x1:

                        isConnectedGettingState = true;
                        MainActivity.mDevice.getBrushingStatus();

                        break;
                    case 0x28:
                        //[1] = area  0x99:mannually Closed.
                        //[3] = isCorrectArea  0x1:correct
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                boolean isCorrect = (values[3] == 1);
                                boolean isNeedToMove = (values[2] == 1);
                                boolean result = (isCorrect == true && isNeedToMove == false);
                                brushProgress(values[1], result ? (byte) 0x1 : (byte) 0x0);
                            }
                        });

                        break;
                    case 0x21:
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //如果牙刷处于开启状态，则开启刷牙指导
                                if (values[1] == 0x9) {
                                    if (dialog_chargeNotification == null) {
                                        dialog_chargeNotification = new
                                                ChargeNotificationDialog(BrushingFragment.this.getContext(), runnable_iv_close);
                                    }
                                    dialog_chargeNotification.show();

                                } else if (values[1] == 0 && isConnectedGettingState == false) {
                                    countDownPrepare();
                                } else {
                                    startBrushing();
                                }
                                if (isConnectedGettingState) {
                                    isConnectedGettingState = false;
                                }
                            }
                        });
                        // MainActivity.mDevice.getBrushingData((byte) 0);
                        break;
                    case 0x13:
                        Common.battery = values[1] & 0xFF;

                        break;
                    case 0x36:
                        MainActivity.mDevice.getHand();

                        int hand = values[1];
                        if (hand == 2) {
                            Common.userInfo.setHand(0); //Right hand
                        } else if (hand == 1) {
                            Common.userInfo.setHand(1); //Left hand
                        }
                        Common.userInfo.SyncToLocal(BrushingFragment.this.getContext());
                        break;

//                    case 0x15:
//
//                        //结束标识符
//                        if (values[1] == (byte) 0xFF) {
//
//                            //刷新最新数据时间戳
//                            Common.userInfo.setLastSyncTime(Calendar.getInstance().getTimeInMillis());
//                            Common.userInfo.SyncToLocal(getContext());
//
//                            return;
//                        }
//
//                        Calendar data_c = Calendar.getInstance();
//
//                        int year = 0, month = 0, day = 0, hours = 0, minutes = 0, seconds = 0;
//                        //0为离线刷牙，1为指导刷牙记录
//                        int type = 1;
//                        year = Util.ConvertBCD2Decimal(values[2]) + 2000;
//                        month = Util.ConvertBCD2Decimal(values[3]) - 1;
//                        day = Util.ConvertBCD2Decimal(values[4]);
//                        if (values[5] >= 0x24) {
//                            //减去0x48
//                            hours = Util.ConvertBCD2Decimal((byte) (values[5] - 48));
//                            type = 0;
//
//                        } else {
//                            hours = Util.ConvertBCD2Decimal(values[5]);
//                        }
//                        minutes = Util.ConvertBCD2Decimal(values[6]);
//                        seconds = Util.ConvertBCD2Decimal(values[7]);
//
//                        data_c.set(year, month, day, hours, minutes, seconds);
//
//                        //新的历史记录
//                        if (data_c.getTimeInMillis() > Common.userInfo.getLastSyncTime()) {
//                            int totalTime = (values[8] & 0xFF) + ((values[9] << 8) & 0xFF00);
//
//                            //牙刷中的离线刷牙历史数据，少于30s 的刷牙时间不做存储。
//                            //大于3分钟也不做存储
//                            if (type == 1) {
//                                if (totalTime < 30 || totalTime > 180) {
//                                    return;
//                                }
//                                //牙刷m中的离线刷牙历史数据，少于30s 的刷牙时间不做存储。
//                                //大于5分钟也不做存储
//                                //离线刷牙时;如果刷满固件所设定的时间:离线刷牙的数据总会多出1~2秒的。
//                                if (Common.userInfo.getBrushTime() + 1 == totalTime ||
//                                        Common.userInfo.getBrushTime() + 2 == totalTime
//                                ) {
//                                    totalTime = Common.userInfo.getBrushTime();
//                                }
//
//                            } else {
//
//                                if (totalTime < 30 || totalTime > 300) {
//                                    return;
//                                }
//
//
//                            }
//
//                            int mode = PreferencesUtils.ReadFromPreferencesInt(getContext(), BrushMode);
//                            BrushingRecord record = new BrushingRecord();
//                            record.setTotalTime(totalTime);
//                            record.setStartTime(data_c);
//
//                            //我这边DBHelper type = 0 是指导刷牙数据,离线刷牙数据是 1
//                            record.setType(type);//牙刷历史数据
//
//                            if (type == 0) {
//                                record.setBrushMode(mode);
//                                int area1 = 0, area2 = 0, area3 = 0, area4 = 0, area5 = 0, area6 = 0;
//                                //下门牙外
//                                if (values[20] == 10) {
//                                    area1 += 1;
//                                }
//
//                                //下门牙内
//                                if (values[21] == 10) {
//                                    area1 += 4;
//                                }
//                                //上门牙外
//                                if (values[22] == 10) {
//                                    area2 += 1;
//                                }
//                                //上门牙内
//                                if (values[23] == 10) {
//                                    area2 += 4;
//                                }
//
//                                //左下外
//                                if (values[24] == 10) {
//                                    area3 += 1;
//                                }
//
//                                //左下中
//                                if (values[25] == 10) {
//                                    area3 += 2;
//                                }
//
//                                //左下内
//                                if (values[26] == 10) {
//                                    area3 += 4;
//                                }
//
//
//                                //左上外
//                                if (values[27] == 10) {
//                                    area4 += 1;
//                                }
//
//                                //左上中
//                                if (values[28] == 10) {
//                                    area4 += 2;
//                                }
//
//                                //左上内
//                                if (values[29] == 10) {
//                                    area4 += 4;
//                                }
//
//                                //右下外
//                                if (values[30] == 10) {
//                                    area5 += 1;
//                                }
//
//                                //右下中
//                                if (values[31] == 10) {
//                                    area5 += 2;
//                                }
//
//                                //右下内
//                                if (values[32] == 10) {
//                                    area5 += 4;
//                                }
//
//
//                                //右上外
//                                if (values[33] == 10) {
//                                    area6 += 1;
//                                }
//
//                                //右上中
//                                if (values[34] == 10) {
//                                    area6 += 2;
//                                }
//
//                                //右上内
//                                if (values[35] == 10) {
//                                    area6 += 4;
//                                }
//
//                                record.setArea1(area1);
//                                record.setArea2(area2);
//                                record.setArea3(area3);
//                                record.setArea4(area4);
//                                record.setArea5(area5);
//                                record.setArea6(area6);
//                            }
//
//                            int percent = (int) ((float) totalTime / (float) Common.userInfo.getBrushTime() * 100);
//
//                            //如果超出离线刷牙时长的设置，还是100%
//                            percent = percent > 100 ? 100 : percent;
//
//                            record.setPercent(percent);
//                            dbHelper.insertBrushRecord(record);
//
//                            //累加刷牙积分
//                            float ratio = (float) totalTime / (float) Common.userInfo.getBrushTime();
//
//                            if (ratio > 1f) {
//                                ratio = 1f;
//                            }
//
//                            //离线刷牙数据统一加10分
//                            Common.userInfo.setScore((int) 10 + Common.userInfo.getScore());
//                            Common.userInfo.SyncToLocal(getContext());
                       //     break;
                      //  }
                }
            }
        }
    };
}